package com.sanpu.kxe.business.repay.presenter;

import com.sanpu.kxe.business.repay.bean.QueryPlanOutput;
import com.sanpu.kxe.business.repay.contract.QueryPlanNewContract;
import com.sanpu.kxe.business.repay.model.RepayModel;
import com.sanpu.kxe.common.interfaces.CommonConfig;

import java.util.List;

import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Description：查询计划
 * Created by 薛勇军 on 2019/5/28.
 */

public class QueryPlanNewPresenter implements QueryPlanNewContract.Presenter {

    private QueryPlanNewContract.View mView;

    private CompositeSubscription mSubscription;

    private String mercCardId;

    public QueryPlanNewPresenter(QueryPlanNewContract.View mView, String mercCardId) {
        this.mView = mView;
        this.mercCardId = mercCardId;
        mSubscription = new CompositeSubscription();
    }

    @Override
    public void cardPlanList(final int nowPage, String planStatus) {
        Subscription subscription = RepayModel.getInstance().cardPlanListForStatus(nowPage, mercCardId, planStatus)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<QueryPlanOutput>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.showErrorText(e);
                        mView.showDataView(null, nowPage == 0);
                        mView.showLoadMore(CommonConfig.LOADMOREFAIL);
                    }

                    @Override
                    public void onNext(List<QueryPlanOutput> queryPlanOutputs) {
                        mView.showDataView(queryPlanOutputs, nowPage == 0);
                        if (queryPlanOutputs != null) {
                            if (queryPlanOutputs.size() < CommonConfig.PAGENUMER) {
                                mView.showLoadMore(CommonConfig.LOADMOREEND);
                            } else {
                                mView.showLoadMore(CommonConfig.LOADMORECOMPLETE);
                            }
                        } else {
                            mView.showLoadMore(CommonConfig.LOADMOREEND);
                        }
                    }
                });
        mSubscription.add(subscription);
    }

    @Override
    public void onDestroyPresenter() {
        if (mSubscription != null && !mSubscription.isUnsubscribed()) {
            mSubscription.unsubscribe();
            mSubscription = null;
        }
        if (mView != null) {
            mView = null;
        }
    }
}
